package com.example.mq2.mqserver.datacenter;

import com.example.mq2.common.MqException;
import com.example.mq2.mqserver.core.Binding;
import com.example.mq2.mqserver.core.Exchange;
import com.example.mq2.mqserver.core.MSGQueue;
import com.example.mq2.mqserver.core.Message;
import com.sun.corba.se.spi.ior.IdentifiableFactory;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 硬盘数据中心(数据库 + 消息文件)
 */
public class DiskDataCenter {

    private DataBaseManager dataBaseManager = new DataBaseManager();
    private MessageFileManager messageFileManage = new MessageFileManager();

    /**
     * 针对数据库和消息文件进行初始化
     */
    public void init() {
        dataBaseManager.init();
        messageFileManage.init();
    }

    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchange() {
        return dataBaseManager.selectExchangeAll();
    }

    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        //还需要创建出对应的队列文件
        messageFileManage.createQueueFile(queue.getName());
    }

    public void deleteQueue(String queueName) {
        dataBaseManager.deleteQueue(queueName);
        //还需要删除对应的队列文件
        messageFileManage.destroyQueueFile(queueName);
    }

    public List<MSGQueue> selectAllQueue() {
        return dataBaseManager.selectQueueAll();
    }

    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBinding() {
        return dataBaseManager.selectBindingAll();
    }

    public void sendMessage(MSGQueue queue, Message message) throws IOException {
        messageFileManage.sendMessage(queue, message);
    }

    public void deleteMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManage.deleteMessage(queue, message);
        //删除消息的同时检验是否要进行 gc
        if(messageFileManage.checkGC(queue.getName())) {
            messageFileManage.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(MSGQueue queue) throws IOException, MqException {
        return messageFileManage.loadAllMessageFromQueue(queue);
    }

}
